package com.xian.cloud.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;


/**
 * @program: cloud-demo
 * @description:
 * @author: xlr
 * @create: 2019-08-09 22:41
 **/
@Slf4j
public class ServerHandler extends SimpleChannelInboundHandler<Object> {

    public static AtomicInteger atomicInteger = new AtomicInteger();

    /**
     *此方法会在接收到服务器数据后调用
     * */
    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) {
        System.out.println("server receive message :"+ msg);
        ctx.channel().writeAndFlush("yes server already accept your message" + msg);
        if(msg.toString().equals("hello$")){
            atomicInteger.getAndIncrement();
        }
        ctx.close();
    }

    /**
     *此方法会在连接到服务器后被调用
     * */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println(atomicInteger.get());
    }

    /**
     *捕捉到异常
     * */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("netty发生错误", cause);
        cause.printStackTrace();
        ctx.close();
    }


    /**
     * channel未连接到远程服务器
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.debug("..............班级【{}】断开连接..............");
        ctx.close();
    }

    /**
     * channelRead执行后触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelReadComplete();
    }

    public static Integer getAtomicInteger() {
        return atomicInteger.get();
    }
}
